//
//  AppDelegate.m
//  PersonalOC
//
//  Created by 韩琴 on 2018/8/15.
//  Copyright © 2018年 韩琴. All rights reserved.
//

#import "AppDelegate.h"
#import <UMCommon/UMCommon.h>
#import <XHLaunchAd.h>

@interface AppDelegate ()<WXApiDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds] ];
    self.window.backgroundColor = UIColor.whiteColor;
    
    //启动页
    [XHLaunchAd setLaunchSourceType:SourceTypeLaunchScreen];
    XHLaunchImageAdConfiguration *imageAdconfiguration = [XHLaunchImageAdConfiguration defaultConfiguration];
    imageAdconfiguration.contentMode =  UIViewContentModeScaleAspectFit;
    NSString *fileUrl = [[NSUserDefaults standardUserDefaults] objectForKey:startPagefilePath];
    if (![LYTools stringIsNil:fileUrl]) {
        imageAdconfiguration.imageNameOrURLString = _imageAddressUrl(fileUrl);
    } else {
        //广告图片URLString/或本地图片名(.jpg/.gif请带上后缀)
        imageAdconfiguration.imageNameOrURLString =@"备用启动页.png";
    }
    [XHLaunchAd imageAdWithImageAdConfiguration:imageAdconfiguration delegate:self];
    
    //获取用户数据
    UserModel *model =  [NSKeyedUnarchiver unarchiveObjectWithFile:_userModelFile];
    if ([LYTools stringIsNil:model.id]) {
        LoginVC *login = [[LoginVC alloc] initWithNibName:@"LoginVC" bundle:nil];
        BaseNavigationController *loginNav = [[BaseNavigationController alloc] initWithRootViewController:login];
        self.window.rootViewController= loginNav;
    } else {
        _userModel =  [NSKeyedUnarchiver unarchiveObjectWithFile:_userModelFile];
        [UserShare dataWithModel:_userModel.mj_keyValues];
        self.window.rootViewController = [[BaseTabBarController alloc] init];
    }
    //判断是否第一次
    BOOL isOne =   [[NSUserDefaults standardUserDefaults] boolForKey:_isOne];
    
    if(isOne==NO)
    {
        
        //引导页
        KSGuaidManager.images = @[[UIImage imageNamed:@"引导页1"],
                                  [UIImage imageNamed:@"引导页2"],
                                  [UIImage imageNamed:@"引导页3"],
                                  ];
        
        KSGuaidManager.shouldDismissWhenDragging = YES;
        [KSGuaidManager begin];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:_isOne];
    }
    
    [self.window makeKeyAndVisible];
    
    // UMConfigure 通用设置，请参考SDKs集成做统一初始化。
    // 以下仅列出U-Share初始化部分
    // U-Share 平台设置
    [UMConfigure initWithAppkey:UM_APP_KEY channel:@"App Store"];
    [self configUSharePlatforms];
    [self confitUShareSettings];
    
    return YES;
}
- (void)confitUShareSettings
{
    /*
     * 打开图片水印
     */
    //[UMSocialGlobal shareInstance].isUsingWaterMark = YES;
    /*
     * 关闭强制验证https，可允许http图片分享，但需要在info.plist设置安全域名
     <key>NSAppTransportSecurity</key>
     <dict>
     <key>NSAllowsArbitraryLoads</key>
     <true/>
     </dict>
     */
    //[UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;
}
- (void)configUSharePlatforms
{
    /* 设置微信的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:APP_ID_FOR_WX appSecret:APP_SECRET_FOR_WX redirectURL:nil];
    /*
     * 移除相应平台的分享，如微信收藏
     */
    //[[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
    /* 设置分享到QQ互联的appID
     * U-Share SDK为了兼容大部分平台命名，统一用appKey和appSecret进行参数设置，而QQ平台仅需将appID作为U-Share的appKey参数传进即可。
     */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:APP_ID_FOR_QQ/*设置QQ平台的appID*/  appSecret:nil redirectURL:nil];
    /* 设置新浪的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:APP_ID_FOR_Sina  appSecret:APP_SECRET_FOR_Sina redirectURL:@"https://sns.whalecloud.com/sina2/callback"];
    
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
//// NOTE: 8.0及以前使用API接口
//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
//     BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
//    if (result) {
//        return result;
//    }
//    if ([url.host isEqualToString:@"safepay"]) {
//        [self alipayResult:url];
//    } else if ([WXApi handleOpenURL:url delegate:self]) {
//        return [WXApi handleOpenURL:url delegate:self];
//    }
//    return YES;
//}
//// NOTE: 9.0以后使用新API接口
//- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
//    if ([url.host isEqualToString:@"safepay"]) {
//        //支付宝支付结果
//        [self alipayResult:url];
//    } else if ([WXApi handleOpenURL:url delegate:self]) {
//        //微信支付结果
//        return [WXApi handleOpenURL:url delegate:self];
//    }
//    return YES;
//}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
        if ([url.host isEqualToString:@"safepay"]) {
            //支付宝支付结果
            [self alipayResult:url];
            return YES;
        } else if ([WXApi handleOpenURL:url delegate:self]) {
            //微信支付结果
            return [WXApi handleOpenURL:url delegate:self];
        }
    }
    return result;
}

#pragma mark——————————微信支付回调
-(void)onResp:(BaseResp*)resp{
    
    //启动微信支付的response
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        NSString *message = nil;
        switch (resp.errCode) {
            case 0:
                message = @"支付成功";
                break;
            case -1:
                message = @"支付失败";
                break;
            case -2:
                message = @"退出支付";
                break;
            default:
                message = @"支付失败";
                break;
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:_wechatPayOver object:nil];
    }
    
    
}
#pragma mark——————————支付宝支付回调
-(void)alipayResult:(NSURL *)url {
    //跳转支付宝钱包进行支付，处理支付结果
    [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
        NSLog(@"这是appdelegt ios9:result = %@",resultDic);
        
        NSString *message = @"";
        switch([[resultDic objectForKey:@"resultStatus"] integerValue])
        {
            case 9000:message = @"订单支付成功";break;
            case 8000:message = @"正在处理中";break;
            case 4000:message = @"订单支付失败";break;
            case 6001:message = @"用户中途取消";break;
            case 6002:message = @"网络连接错误";break;
            default:message = @"未知错误";
        }
        //发送通知
        [[NSNotificationCenter defaultCenter]postNotificationName:_aliPayOver object:message];
    }];
}
@end
